// pages/home/home.js
var Zan = require('../../dist/index');
var bananer = require('../../template/HomeTemp.js');
var baseInfo = require('../../utils/base_info.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
// 获取应用实例
let app = getApp()
let count = 0;
let start1 = 0;

/**
 * 所有商品 0 (旧数据) 
 * 商品详情 1 
 * 商品分类 2 
 * 优惠券列表 3 
 * 商品搜索 4 
 * 到店自提 5(旧数据) 
 * 拼团详情 6
 * 文章详情 7 
 * 文章分类 8 
 * 拼团列表 9
 * 积分商品列表 10 
 * 积分商品详情 11 
 * 分销页面 12 
 * 门店列表 13 
 * 门店详情 14
 */
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    bananer: {
      autoplay: true,
      interval: 5000,
      duration: 300,
      indicatorDots: true,
      circular: true
    },
    frame: [],
    popOn: null,
    coupon: [],
    showModalStatus: false,
    store: null,
    screenHeight: 0,
    isyouhuishow: false,
    showCenterBtn: true,
    showFillBtn: false,
    temp: '',
    mobiles:false,
    shared:'',
    isFacePayment:2,
    itemLinkId:'',
    items:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.userLocation" 这个 scope
    let that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log("允许获取地理位置++++++++++++++++++");
        let latitude = res.latitude;
        let longitude = res.longitude;
        that.setData({
          lng: longitude,
          lat: latitude
        })
        if (options.storeId){
          app.globalData.storeId = options.storeId;
          network._post_json(that, api.storeDetails, { id: options.storeId }, successStoreDetails);
          
        }else{
          network._post_json(that, api.nearbyStore, { lng: longitude, lat: latitude }, successStore);
        }
        
      },
      fail:function(res){
        console.log("拒绝获取地理位置++++++++++++++++++");
        that.setData({
          lng: 114.31171,
          lat: 30.59868
        })
        if (options.storeId) {
          app.globalData.storeId = options.storeId;
          network._post_json(that, api.storeDetails, { id: options.storeId }, successStoreDetails);
        } else {
          network._post_json(that, api.nearbyStore, { lng: that.data.lng, lat: that.data.lat }, successStore);
        }
        
      }
    })
    

    // 获取回调门店信息
    WxNotificationCenter.addNotification("GetStoreInfo", this.getStoreInfo, this)
    // 注册列表刷新事件
    WxNotificationCenter.addNotification("articleRefreshNotification", this.refreshNotification, this);
    if (options.shared) {
      this.setData({
        shared: options.shared,
      })
    }

    this.setData({
      utils: utils,
      height: utils.windowSize().winWidth / 750 * 378
    });

    this.setData({
      bananer: {
        autoplay: true,
        interval: 5000,
        duration: 300,
        indicatorDots: true,
        circular: true,
        height: utils.windowSize().winWidth / 750 * 378
      }
    })
    app.userInfoCallback = res => {
      console.log("===========userInfo============");
      console.log(app.globalData.userInfo);
      if (app.globalData.userInfo.mobile) {
        this.setData({
          mobiles: true
        })
      }
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      showModalStatus: false
    })
  },

  /**
  * 生命周期函数--监听页面卸载
  */
  onUnload: function () {
    WxNotificationCenter.removeNotification("GetStoreInfo", this);
    WxNotificationCenter.removeNotification("articleRefreshNotification", this);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    if (app.globalData.store.id){
      this.setData({
        frame: []
      })
      console.log(app.globalData.store.id);
      network._post_json(this, api.getHomeFarem, { storeId: app.globalData.store.id }, success);
    }
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  onBananerItemClick: function (e) {
    bananer.onBananerItemClick(this, e);
  },

  onNavigateItemClick: function (e) {
    bananer.onNavigateItemClick(this, e);
  },

  onRecommendItemClick: function (e) {
    bananer.onRecommendItemClick(this, e);
  },

  onSpellProductItemClick: function (e) {
    bananer.onSpellProductItemClick(this, e);
  },

  onintegralItemClick: function (e) {
    bananer.onintegralItemClick(this, e);
  },

  onArticleItemClick: function (e) {
    bananer.onArticleItemClick(this, e);
  },

  onImageHItemClick: function (e) {
    bananer.onImageHItemClick(this, e);
  },

  onVideoItemClick: function (e) {
    bananer.onVideoItemClick(this, e);
  },

  powerDrawer: function (e) {
    bananer.powerDrawer(this, e);
  },

  onAdvertItemClick: function (e) {
    bananer.onAdvertItemClick(this, e);
  },
  // 领取优惠券
  // receiveCoupon: function (e) {
  //   this.setData({
  //     showModalStatus: false
  //   })
  //   bananer.receiveCoupon(this, e)
  // },
  // 领取优惠券
  receiveCoupon:function (e) {
    console.log("领取优惠券mobiles" + this.data.mobiles);
    var item = e.currentTarget.dataset.item;
    this.setData({
      itemLinkId: item.linkId
    })
    if (item.isGetPhone == 1){
      let that = this;
      if (that.data.mobiles){
        network._post_json(that, api.receiveCoupon, { couponId: item.linkId }, Receivesuccess);
      }else{
        if (e.detail.encryptedData) {
          // 校验用户当前session_key是否有效
          wx.checkSession({
            success: function () {
              network._post_json(that, api.decodePhone, { appId: app.globalData.appId, encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: app.globalData.sessionKey }, mobileSuccess);
            },
            fail: function () {
              // session_key 已经失效，重新登录
              wx.login({
                success: function (res) {
                  // 获取jsCode
                  let jsCode = res.code;
                  wx.request({
                    url: api.getOpenId,
                    method: 'POST',
                    data: { prAppid: app.globalData.appId, code: jsCode },
                    success: function (res) {
                      console.log(res.data);
                      let sessionKey = res.data.data.session_key;
                      network._post_json(that, api.decodePhone, { appId: app.globalData.appId, encryptedData: e.detail.encryptedData, iv: e.detail.iv, sessionKey: sessionKey }, mobileSuccess);
                    }
                  })
                },
                fail: function (res) {
                  console.log(res);
                }
              })
            }
          })
        }
      }
      
    }else{
      network._post_json(this, api.receiveCoupon, { couponId: item.linkId }, Receivesuccess);

    }
    
  },

  Refresh() {
    this.onPullDownRefresh();
  },
  //点击领取优惠券
  clickhongbao: function (e) {
    bananer.clickhongbao(this, e)
  },

  /**
   * 选择店铺
   */
  goStore: function (e) {
    wx.navigateTo({
      url: '/pages/myself/store/StoreInfo' + '?lng=' + this.data.lng + '&lat=' + this.data.lat + '&backTag=' + 1
    })
  },

  /**
   * 回调门店信息
   */
  getStoreInfo: function (e) {
    this.setData({
      store: e,
      frame: [],
      items: []
    })
    app.globalData.store = e
    network._post_json(this, api.getHomeFarem, { storeId: e.id }, success);
    network._post_page_json(this, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
    // wx.removeStorageSync('linkId');
    wx.setStorageSync("linkId", 0);
    console.log(e);

  },
  //文章查看次数
  refreshNotification:function(e){
    this.onPullDownRefresh();
  }
}))
var mobileSuccess = function (that, res) {
  if (res.data.data) {
    app.globalData.userInfo.mobile = res.data.data.mobile;
    that.setData({
      userInfo: app.globalData.userInfo
    });
    network._post_json(that, api.receiveCoupon, { couponId: that.data.itemLinkId }, Receivesuccess);
    that.setData({
      mobiles: true
    })
  }
}
var successCar = function(that,res){
  if(res.data.data){
    that.setData({
      items: res.data.data.list,
    })
    
    // if (res.data.data.list.length > 0) {
    //   let allProId = [];
    //   for (var c = 0; c < that.data.items.length; c++) {
    //     let ProIdItems = that.data.items[c].id;
    //     allProId.push(ProIdItems);
    //   }
    // allProId = allProId.join(',');
    //   network._post_json(that, api.delShoppingCart, { shoppingCarId: allProId, is_del: 1 }, delSuccess);
    // }
  }
}
// var delSuccess = function (that, res) {
//   if (res.data.data) {
//     network._post_page_json(that, api.getShoppingCartList, start1, { userId: app.globalData.userId, storeId: app.globalData.store.id }, successCar);
//   }
// }
//门店
var successStore = function (that, res) {
  if (res.data.data) {
    that.setData({
      store: res.data.data,
      frame: [],
     
    })
    app.globalData.store = res.data.data;
    app.globalData.isFacePayment = res.data.data.isFacePayment;
    console.log("isFacePayment"+app.globalData.isFacePayment);
    network._post_json(that, api.getCoupon, {}, popOnSuccess);
    network._post_json(that, api.getHomeFarem, { storeId: res.data.data.id }, success);
    
    // console.log("userInfoid=============="+app.globalData.userInfo.id);
    // console.log("绑定上级用户" + that.data.shared);
    if (that.data.shared && that.data.shared != app.globalData.userInfo.id && !app.globalData.userInfo.chiefUserId) {
      console.log("==============bindUser==============");

      console.log("绑定上级用户" + that.data.shared);
      network._post_json(that, api.bindUser, { chiefUserId: that.data.shared }, bindSuccess);
    }
  }
}
var successStoreDetails = function(that,res){
  if(res.data.data){
    console.log(res.data.data);
    that.setData({
      store: res.data.data,
      frame: [],
    })
    app.globalData.store = res.data.data;
    app.globalData.isFacePayment = res.data.data.isFacePayment;
    console.log("isFacePayment" + app.globalData.isFacePayment);
    network._post_json(that, api.getCoupon, {}, popOnSuccess);
    network._post_json(that, api.getHomeFarem, { storeId: res.data.data.id }, success);

    if (that.data.shared && that.data.shared != app.globalData.userInfo.id && !app.globalData.userInfo.chiefUserId) {
      console.log("==============bindUser==============");

      console.log("绑定上级用户" + that.data.shared);
      network._post_json(that, api.bindUser, { chiefUserId: that.data.shared }, bindSuccess);
    }
  }
}
// 首页控件请求返回结果
var success = function (that, res) {

  // 首页控件请求
  if (res.data.data) {
    // for (var i = 0; i < res.data.data.length; i++) {
    //   if (res.data.data.backgroud) {
    //     res.data.data.backgroud = colorRGB2Hex(res.data.data.backgroud);
    //   } else {
    //     res.data.data.backgroud = '#ffffff';
    //   }

    //   if (res.data.data.type == 5) {
    //     let video = [];
    //     for (let j = 0; j < res.data.data.applet[i].sub.length; j++) {
    //       that['videoContext' + res.data.data.applet[i].sub[j].id] = wx.createVideoContext(res.data.data.applet[i].sub[j].id, that);
    //     }
    //   }

    //   if (res.data.data.applet[i].type == 7) {
    //     for (let j = 0; j < res.data.data.applet[i].sub.length; j++) {
    //       res.data.data.applet[i].sub[j].createDate = utils.formatDate06(new Date(res.data.data.applet[i].sub[j].createDate))
    //     }
    //   }
    // }
    that.setData({
      frame: that.data.frame.concat(res.data.data),
      // popOn: res.data.data.popOn
    })
    // if (res.data.data.popOn) {
    //   if (res.data.data.popOn.status == 1) {
    //     if (res.data.data.popOn.type == '广告') {
    //       that.setData({
    //         showModalStatus: true
    //       })
    //     } else {
    //       if (res.data.data.popOn.linkId) {
    //         var couponId = res.data.data.popOn.linkId.split(",")
    //         network._post_json(that, api.getCoupon, { couponId: couponId }, couponSuccess);
    //       }
    //     }
    //   }
    // }
  }
}

var popOnSuccess = function (that, res) {
  if (res.data.data) {
    var popOn = res.data.data;
    // for (var i = 0; i < coupon.length; i++) {
    //   coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime))
    //   coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime))
    // }
    that.setData({
      popOn: popOn,
      showModalStatus: true
    })
  }
}


// var couponSuccess = function (that, res) {

//   if (res.data.data) {
//     var coupon = res.data.data;
//     for (var i = 0; i < coupon.length; i++) {
//       coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime))
//       coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime))
//     }
//     that.setData({
//       coupon: coupon,
//       showModalStatus: true
//     })
//   }
// }

var bind = function (options) {
  // if (options.scene) {
  //   var scene = decodeURIComponent(options.scene);
  //   if (scene.substring(0, 1) == 'u') {
  //     wx.request({
  //       url: api.bindUserFormQRcode,
  //       data: {
  //         openId: app.globalData.openId,
  //         userId: app.globalData.userId,
  //         tenantId: app.globalData.tenantId,
  //         distributorId: scene.substring(2, scene.length),
  //       },
  //       method: 'POST',
  //       success: function (res) {
  //       }
  //     });
  //   } else {
  //     app.globalData.storeId == scene.substring(2, scene.length);
  //   }
  // }
  
  
  // if (options.shared) {
  //   console.log("==============bindUser==============");
    // console.log("绑定上级用户"+options.shared);
    // wx.request({
    //   url: api.bindUser,
    //   data: {
    //     chiefUserId: options.shared
    //   },
    //   method: 'POST',
    //   success: function (res) {
    //     console.log("绑定上级用户成功");
    //   }
    // });
    // network._post_json(this, api.bindUser, { chiefUserId: options.shared }, bindSuccess);
  // }
}

var bindSuccess = function (that, res) {

}

var colorRGB2Hex = function (color) {
  var rgb = color.split(',');
  var r = parseInt(rgb[0].split('(')[1]);
  var g = parseInt(rgb[1]);
  var b = parseInt(rgb[2].split(')')[0]);

  var hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  return hex;
}
// 获取优惠券列表结果
var Receivesuccess = function (that, res) {
  if (res.data.data) {
    if (res.data.data == '已领完') {
      // wx.showToast({
      //   title: '已领完'
      // })
      that.showZanTopTips('已领完');
    } else if (res.data.data == '存在已下架优惠券') {
      that.showZanTopTips('存在已下架优惠券，请刷新');
    }
    else {
      // wx.showToast({
      //   title: '领取成功',
      //   duration: 5000
      // })
      that.showZanToast('领取成功');
      WxNotificationCenter.postNotificationName('couponRefreshNotification');
    }
  }
}